/* Includes ------------------------------------------------------------------*/
#include "task_sensor.h"
#include "cmsis_os.h"
#include "battery_monitor.h"
#include "rs485.h"
#include "oled.h"
#include "usart.h"


extern osMessageQueueId_t batteryQueueHandle;   //电池队列
extern osMessageQueueId_t sensorQueueHandle;    //传感器队列
extern osSemaphoreId_t sensorSemHandle;         //传感器二值信号量

extern osThreadId_t DisplayTaskHandle;
extern osThreadId_t CommTaskHandle;



/* Private function prototypes -----------------------------------------------*/
void Sensor_Task(void *argument)
{

    (void)argument;  // 防止未使用的参数警告
    BatteryData_t batteryData;            //函数内部使用

    SoilSensor_Init(&huart1, sensorQueueHandle);   //土壤传感器初始化

    for(;;)
    {

        // 等待 RTC Alarm 或按键信号量
        osSemaphoreAcquire(sensorSemHandle, osWaitForever);

        // ---------------------获取电池数据---------------------
        batteryData.voltage = BatteryMonitor_ReadVoltage();
        batteryData.percentage = BatteryMonitor_VoltageToPercent(batteryData.voltage);

        // 将数据发送到队列
        if (osMessageQueuePut(batteryQueueHandle, &batteryData, 0, 0) != osOK) {
            // 如果队列满了或者发送失败，可以在这里做错误处理
        }

        // ----------------- 上电控制 -----------------
        HAL_GPIO_WritePin(EN12V_GPIO_Port, EN12V_Pin, GPIO_PIN_SET);  // 开启上电

        // ----------------- 开始显示数据采集进度条 -----------------
        uint32_t start_time = osKernelGetTickCount();
        uint32_t elapsed_time = 0;

        while (elapsed_time < 2500) {
            elapsed_time = osKernelGetTickCount() - start_time;
            Display_LoadingBar(elapsed_time);  // 显示进度条
            osDelay(50);  // 延迟，避免过度占用CPU
        }

        // --------------------读取土壤传感器数据-------------------
        if (SoilSensor_ReadData() == SENSOR_OK)
        {
            osThreadFlagsSet(DisplayTaskHandle, 0x01);
            osThreadFlagsSet(CommTaskHandle, 0x01);
        }

    }

}

